<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--患者数据-->
            <el-row style="border-bottom:1px solid #000">
                <el-form :model="queryParams" ref="queryForm" :rules="queryFormRules" size="small" :inline="true"
                    label-width="80px">
                    <el-form-item label="患者手机" prop="patientPhone">
                        <el-input v-model="queryParams.patientPhone" placeholder="请输入患者手机" clearable style="width: 240px" />
                    </el-form-item>
                    <el-form-item label="专病名称" prop="diseaseId">
                        <el-select v-model="queryParams.diseaseId" placeholder="请选择专病名称" style="width: 240px" clearable>
                            <el-option v-for="dict in dict.type.sys_manage_diseases" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="患者卡号">
                        <el-input v-model="queryParams.cardNumber" placeholder="请输入患者卡号" clearable style="width: 240px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row style="margin-top:15px;border-bottom:1px solid #000">
                <el-form :model="baseInfo" ref="baseInfoForm" size="small" :inline="true" label-width="78px"
                    :rules="baseInfoFormRules">
                    <el-row>
                        <el-form-item label="患者卡号" prop="cardNumber">
                            <el-input v-model="baseInfo.cardNumber" placeholder="请输入患者卡号" clearable style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="患者姓名" prop="patientName">
                            <el-input v-model="baseInfo.patientName" placeholder="请输入患者姓名" clearable style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="患者性别" prop="sex">
                            <el-select v-model="baseInfo.sex" placeholder="请选择患者性别" style="width: 240px">
                                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="出生日期">
                            <el-date-picker v-model="baseInfo.birthDate" type="date" placeholder="出生日期" style="width: 240px"
                                value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-form-item label="患者手机" prop="patientPhone">
                            <el-input v-model="baseInfo.patientPhone" placeholder="请输入患者手机" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="患者地址" prop="area">
                            <el-cascader v-model="baseInfo.area" placeholder="请选择患者地址" class="picker-form"
                                :options="areaList" :props="{ children: 'childrenList', value: 'id', label: 'name' }"
                                style="width: 240px">
                            </el-cascader>
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input v-model="baseInfo.address" placeholder="请输入详细地址" clearable style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="患者类别" prop="category">
                            <el-select v-model="baseInfo.category" placeholder="请选择患者类别" style="width: 240px">
                                <el-option v-for="dict in dict.type.sys_user_category" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-row>
                </el-form>
            </el-row>
            <el-row style="margin-top:15px;">
                <el-form :model="visitInfo" ref="visitInfoForm" size="small" :inline="true" label-width="78px"
                    :rules="visitInfoFormRules">
                    <el-form-item label="就诊日期" prop="createTime">
                        <el-date-picker v-model="visitInfo.createTime" type="datetime" placeholder="就诊日期"
                            style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="就诊门诊" prop="deptId">
                        <treeselect v-model="visitInfo.deptId" :options="deptOptions" :show-count="true"
                            style="width: 240px" placeholder="请选择就诊门诊" />
                    </el-form-item>
                    <el-form-item label="专病名称" prop="diseaseId">
                        <el-select v-model="visitInfo.diseaseId" placeholder="请选择专病名称" style="width: 240px"
                            @change="getListClassify">
                            <el-option v-for="dict in dict.type.sys_manage_diseases" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专病分类" prop="diseaseClassifyId">
                        <el-select v-model="visitInfo.diseaseClassifyId" placeholder="请选择专病分类" style="width: 240px">
                            <el-option v-for="item in classifyList" :key="item.diseaseClassifyId"
                                :label="item.diseaseClassifyName" :value="item.diseaseClassifyId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专属医生" prop="doctorId">
                        <el-select v-model="visitInfo.doctorId" placeholder="请选择专属医生" style="width: 240px">
                            <el-option v-for="item in doctorList" :key="item.userId" :label="item.userName"
                                :value="item.userId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="治疗状态" prop="status">
                        <el-select v-model="visitInfo.status" placeholder="请选择治疗状态" style="width: 240px">
                            <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="初诊复诊">
                        <el-radio-group v-model="visitInfo.visitStatus" style="width: 240px">
                            <el-radio v-for="item in visitStatusList" :key="item.id"
                                :label="item.id">{{ item.name }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <div style="display:flex;justify-content:center">

                        <el-button type="primary" size="mini" @click="saveBaseInfo">
                            保 存
                        </el-button>
                    </div>
                </el-form>
            </el-row>
        </el-row>

        <el-dialog title="就诊记录详情" :visible.sync="tabsOpen" width="700px" append-to-body>
            <tabs />
        </el-dialog>
    </div>
</template>

<script>
import { listUser, deptTreeSelect } from "@/api/system/user";
import { listClassify } from "@/api/system/classify";
import {
    addressJson,
    findPatient,
    addVisit,
    delVisit,
    updatePhoto,
    batchAddPatientPlan,
} from "@/api/patients/personal";
import { listPhotos, listPlanByVisitId } from "@/api/patients/patient";
import { listPlan } from "@/api/system/plan";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import tabs from "@/views/patients/personal/tabs";
export default {
    name: "addVisitDialog",
    components: { tabs },
    dicts: [
        "sys_user_sex",
        "sys_manage_diseases",
        "sys_diagnosis_status",
        "photo_upload_type",
        "photo_lighting_type",
        "sys_plan_category",
        "sys_dosage_unit",
        "sys_dosage_frequency",
        "sys_plan_usage",
        "sys_user_category",
    ],
    components: { Treeselect },
    data() {
        //验证手机号的规则;
        var checkMobile = (rule, value, cb) => {
            // 验证手机号的正则表达式
            const regMobile =
                /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
            if (regMobile.test(value)) {
                return cb();
            }
            cb(new Error("请输入合法的手机号"));
        };
        return {
            baseUrl: process.env.VUE_APP_BASE_API,
            activeName: "medicalRecords",
            // 省市区
            areaList: [],
            // 查询参数
            queryParams: {
                patientPhone: undefined,
            },
            queryFormRules: {
                patientPhone: [
                    {
                        required: true,
                        message: "患者手机号不能为空",
                        trigger: "blur",
                    },
                    {
                        validator: checkMobile,
                        message: "请输入正确的手机号码",
                        trigger: "blur",
                    },
                ],
            },
            baseInfo: {
                patientId: undefined,
                cardNumber: undefined,
                patientName: undefined,
                sex: undefined,
                birthDate: undefined,
                patientPhone: undefined,
                area: undefined,
                address: undefined,
            },
            baseInfoFormRules: {
                patientName: [
                    {
                        required: true,
                        message: "患者姓名不能为空",
                        trigger: "blur",
                    },
                ],
                sex: [
                    {
                        required: true,
                        message: "患者性别不能为空",
                        trigger: "blur",
                    },
                ],
                patientPhone: [
                    {
                        required: true,
                        message: "患者手机号不能为空",
                        trigger: "blur",
                    },
                    {
                        validator: checkMobile,
                        message: "请输入正确的手机号码",
                        trigger: "blur",
                    },
                ],
                area: [
                    {
                        required: true,
                        message: "患者地址不能为空",
                        trigger: "blur",
                    },
                ],
            },

            visitInfo: {
                createTime: undefined,
                deptId: undefined,
                visitId: undefined,
                diseaseId: undefined,
                diseaseClassifyId: undefined,
                doctorId: undefined,
                status: undefined,
                visitStatus: undefined,
                parentId: null,
            },
            // 科室树选项
            deptOptions: undefined,
            visitInfoFormRules: {
                createTime: [
                    {
                        required: true,
                        message: "就诊日期不能为空",
                        trigger: "blur",
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: "科室不能为空",
                        trigger: "blur",
                    },
                ],
                diseaseId: [
                    {
                        required: true,
                        message: "专病名称不能为空",
                        trigger: "blur",
                    },
                ],
                diseaseClassifyId: [
                    {
                        required: true,
                        message: "专病分类不能为空",
                        trigger: "blur",
                    },
                ],
                doctorId: [
                    {
                        required: true,
                        message: "专属医生不能为空",
                        trigger: "blur",
                    },
                ],
                status: [
                    {
                        required: true,
                        message: "诊断状态不能为空",
                        trigger: "blur",
                    },
                ],
            },
            //专病分类
            classifyList: [
                { diseaseClassifyId: null, diseaseClassifyName: null },
            ],
            doctorList: [],
            visitStatusList: [
                { id: 1, name: "初诊" },
                { id: 2, name: "复诊" },
            ],
            pictureForm: {},
            pictureFormRules: {
                diseaseId: [
                    {
                        required: true,
                        message: "请选择专病名称",
                        trigger: "blur",
                    },
                ],
            },
            picData: {},
            srcList: [],
            medicalRecordsList: [],
            tabsOpen: false,
            isRequest: true,
            planCategoryData: { oralDrug: [], externalUsedDrug: [] },
            oralDrugCheckList: [],
            externalUsedDrugCheckList: [],
            loading: false,
            finishStatus: false,
        };
    },
    watch: {},
    created() {
        this.getAddressData();
        this.getDoctorData();
        this.getDeptTree();
    },
    computed: {},
    methods: {
        /**tab-click */
        tabHandleClick(tab) {
            if (tab.name === "pic") {
                this.getPhotoListByVisitId();
            }
            if (tab.name === "plan") {
                this.getPlanListByVisitId();
            }
        },
        getPhotoListByVisitId() {
            console.log("11111111111111", this.visitInfo.visitId);
            listPhotos({ visitId: this.visitInfo.visitId }).then(
                (res) => {
                    if (res.rows.length > 0) {
                        this.picData = res.rows;
                    } else {
                        this.picData = [];
                    }
                }
            );
        },
        getPlanListByVisitId() {
            this.oralDrug = [];
            this.externalUsedDrug = [];
            listPlanByVisitId({ visitId: this.visitInfo.visitId }).then(
                (res) => {
                    const result = res.rows;
                    result.forEach((item) => {
                        if (item.planCategoryId === "0") {
                            this.oralDrug.push(item);
                        }
                        if (item.planCategoryId === "1") {
                            this.externalUsedDrug.push(item);
                        }
                    });
                }
            );
        },
        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then((response) => {
                this.deptOptions = response.data;
            });
        },

        //就诊记录保存
        saveBaseInfo() {
            if (this.baseInfo.patientId) {
                this.$refs["visitInfoForm"].validate((valid) => {
                    if (valid) {
                        let mData = {
                            patientId: this.baseInfo.patientId,
                            visitId: null,
                        };
                        Object.keys(this.visitInfo).forEach((key) => {
                            mData[key] = this.visitInfo[key];
                        });
                        addVisit(mData).then((res) => {
                            this.loading = true;
                            this.visitInfo.visitId = res.data.visitId;
                            this.$emit("closeVisitDialog");
                            this.loading = false;
                            this.$message.success("保存成功");
                        });
                    }
                });
            } else {
                this.$refs["baseInfoForm"].validate((valid) => {
                    if (valid) {
                        this.$refs["visitInfoForm"].validate((valid) => {
                            if (valid) {
                                this.baseInfo.provinceId =
                                    this.baseInfo.area[0];
                                this.baseInfo.cityId = this.baseInfo.area[1];
                                this.baseInfo.countyId = this.baseInfo.area[2];
                                let mData = {
                                    patientId: null,
                                    visitId: null,
                                    sysPatient: this.baseInfo,
                                };
                                Object.keys(this.visitInfo).forEach((key) => {
                                    mData[key] = this.visitInfo[key];
                                });
                                addVisit(mData).then((res) => {
                                    this.loading = true;
                                    this.baseInfo.patientId =
                                        res.data.patientId;
                                    this.visitInfo.visitId = res.data.visitId;
                                    this.$emit("closeVisitDialog");
                                    this.loading = false;
                                    this.$message.success("保存成功");
                                });
                            }
                        });
                    }
                });
            }
        },
        //图片保存
        savePics() {
            this.dict.type.sys_plan_category.forEach((item) => {
                const mData = {
                    pageNum: 1,
                    pageSize: 1000,
                    diseaseId: this.visitInfo.diseaseId,
                    planCategoryId: String(item.value),
                };
                if (item.value === "0") {
                    item.name = "oralDrug";
                }
                if (item.value === "1") {
                    item.name = "externalUsedDrug";
                }
                listPlan(mData).then((res) => {
                    this.planCategoryData[item.name] = res.rows;
                });
            });
            this.$refs["pictureForm"].validate((valid) => {
                if (valid) {
                    if (this.baseInfo.patientId) {
                        if (this.pictureForm.photoId) {
                            const mData = {
                                patientId: this.baseInfo.patientId,
                                visitId: this.visitInfo.visitId,
                                photoId: this.pictureForm.photoId,
                                photoLightingType:
                                    this.pictureForm.photoLightingType,
                                photoUploadType:
                                    this.pictureForm.photoUploadType,
                            };
                            updatePhoto(mData).then((res) => {
                                this.loading = true;
                                this.step = 2;
                                this.loading = false;
                                console.log(this.planCategoryData);
                            });
                        } else {
                            this.$message.warning("至少需要选择一组照片");
                        }
                    }
                }
            });
        },
        //保存处方
        savePlan() {
            if (
                this.oralDrugCheckList.length > 0 ||
                this.externalUsedDrugCheckList.length > 0
            ) {
                let planArr = [];
                this.oralDrugCheckList.forEach((item) => {
                    this.planCategoryData.oralDrug.forEach((it) => {
                        it.patientId = this.baseInfo.patientId;
                        it.visitId = this.visitInfo.visitId;
                        if (item == it.planId) {
                            planArr.push(it);
                        }
                    });
                });
                this.externalUsedDrugCheckList.forEach((item) => {
                    this.planCategoryData.externalUsedDrug.forEach((it) => {
                        it.patientId = this.baseInfo.patientId;
                        it.visitId = this.visitInfo.visitId;
                        if (item == it.planId) {
                            planArr.push(it);
                        }
                    });
                });
                planArr.forEach((itSelf) => {
                    delete itSelf.planId;
                    delete itSelf.createTime;
                    delete itSelf.updateTime;
                    delete itSelf.createBy;
                });
                batchAddPatientPlan(planArr).then((res) => {
                    this.step = 0;
                    this.resetAllData();
                    this.$message.success("就诊录入已完成");
                });
            } else {
                this.$message.warning("请至少选择一项方案");
            }
        },

        resetAllData() {
            this.$refs["baseInfoForm"].resetFields();
            this.$refs["visitInfoForm"].resetFields();
            this.medicalRecordsList = [];
        },
        detail(data) {
            this.tabsOpen = true;
        },
        deleteDetail(data) {
            delVisit(data.visitId).then((res) => {
                this.handleQuery();
                this.$message.success("删除成功");
            });
        },
        cancel() { },

        handleClick(tab, event) {
            console.log(tab, event);
        },
        getPicPreviewList(it) {
            this.srcList = [
                this.baseUrl + it.leftPhotoAddress,
                this.baseUrl + it.middlePhotoAddress,
                this.baseUrl + it.rightPhotoAddress,
            ];
        },
        getDoctorData() {
            listUser({ pageNum: 1, pageSize: 1000, roleId: 101 }).then(
                (res) => {
                    this.doctorList = res.rows;
                }
            );
        },
        getAddressData() {
            addressJson().then((res) => {
                this.areaList = res.data;
            });
        },

        handleQuery() {
            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    findPatient(this.queryParams).then((res) => {
                        let resultPatient = res.data.patient;
                        if (resultPatient) {
                            Object.keys(this.baseInfo).forEach((key) => {
                                this.baseInfo[key] = resultPatient[key];
                            });
                            this.baseInfo.area = [
                                Number(resultPatient.provinceId),
                                Number(resultPatient.cityId),
                                Number(resultPatient.countyId),
                            ];
                        } else {
                            Object.keys(this.baseInfo).forEach((key) => {
                                this.baseInfo[key] = null;
                            });
                            this.baseInfo.area = [null, null, null];
                        }
                        let result = res.data.visits;
                        result.forEach((item) => {
                            item.visitStatus = 1;
                            item.name =
                                item.createTime +
                                "(初诊)" +
                                this.matchDict(
                                    "sys_manage_diseases",
                                    item.diseaseId
                                ) +
                                "-" +
                                item.diseaseClassifyName +
                                "-" +
                                this.matchDoctor(item.doctorId);
                            item.children.forEach((it) => {
                                item.visitStatus = 2;
                                it.name =
                                    it.createTime +
                                    "(复诊)" +
                                    this.matchDict(
                                        "sys_manage_diseases",
                                        it.diseaseId
                                    ) +
                                    "-" +
                                    it.diseaseClassifyName +
                                    "-" +
                                    this.matchDoctor(it.doctorId);
                            });
                        });
                        this.medicalRecordsList = result;
                    });
                }
            });
        },
        refresh() {
            location.reload();
        },
        getListClassify(value) {
            const findResult = this.medicalRecordsList.find((item) => {
                return item.diseaseId === value;
            });
            if (findResult) {
                this.visitInfo.visitStatus = 2;
                this.visitInfo.parentId = findResult.visitId;
            } else {
                this.visitInfo.visitStatus = 1;
                this.visitInfo.parentId = null;
            }

            listClassify({
                pageNum: 1,
                pageSize: 1000,
                diseaseId: Number(value),
            }).then((response) => {
                this.classifyList = response.rows;
            });
        },
        /** id转化成对应的文字 */
        matchDict: function (key, id) {
            let _this = this;
            const result = _this.dict.type[key];
            let textValue = "";
            result.forEach((item) => {
                if (item.raw.dictValue == id) {
                    textValue = item.raw.dictLabel;
                }
            });
            return textValue;
        },
        /** doctorId转化成对应的医生名字 */
        matchDoctor(doctorId) {
            return this.doctorList.find((item) => {
                return item.userId === doctorId;
            }).userName;
        },
    },
};
</script>

<style scoped>
.medical-records {
    padding: 5px;
    cursor: pointer;
    border-bottom: 1px solid #000;
}

.medical-records:hover {
    background-color: #1890ff;
}

.redColor {
    color: red;
}

.plan-row {
    margin: 15px 0;
    line-height: 28px;
}

.el-checkbox-group {
    font-size: 14px;
}
</style>